import { Injectable, NotFoundException } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class UploadService {
  private readonly imageDir = path.join(process.cwd(), 'src/public');

  // 查找文件是否存在
  findFile(filename: string): boolean {
    console.log('imageDir',this.imageDir);
    
    return fs.existsSync(path.join(this.imageDir, filename));
  }

  // 读取文件内容（返回 Buffer）
  readFile(filename: string): Buffer {
    const filePath = path.join(this.imageDir, filename);
    if (!fs.existsSync(filePath)) {
      throw new NotFoundException('文件不存在');
    }
    return fs.readFileSync(filePath);
  }

  // 删除文件
  deleteFile(filename: string): boolean {
    const filePath = path.join(this.imageDir, filename);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      return true;
    }
    throw new NotFoundException('文件不存在');
  }

  // 更新/覆盖文件
  updateFile(filename: string, buffer: Buffer): boolean {
    const filePath = path.join(this.imageDir, filename);
    fs.writeFileSync(filePath, buffer);
    return true;
  }

  // 获取 images 目录下所有文件名
  listFiles(): string[] {
    return fs.readdirSync(this.imageDir);
  }
}
